package com.zy.community.mini.factory;

import com.zy.community.common.utils.StringUtils;
import com.zy.community.community.domain.ZyVisitor;
import com.zy.community.community.mapper.ZyOwnerMapper;
import com.zy.community.framework.security.mini.MiniContextUtils;
import com.zy.community.web.controller.mini.index.dto.VisitorDto;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
public class VisitorFactory {
    @Resource
    private ZyOwnerMapper zyOwnerMapper;

    /**
     * 实例工厂 将dto-->Visitor
     * @param dto dto
     * @return 访客持久实体
     */
    public ZyVisitor createVisitorByDto(VisitorDto dto){
        if (dto==null) return null;
        ZyVisitor visitor = new ZyVisitor();
        visitor.setVisitorDate(dto.getVisitorDate());
        visitor.setVisitorName(dto.getVisitorName());
        visitor.setVisitorPhoneNumber(dto.getVisitorPhone());
        String openId = MiniContextUtils.getOpenId();
        if (!StringUtils.isEmpty(openId)) {
            visitor.setCreateByOpenId(openId);
            visitor.setCreateById(zyOwnerMapper.findOwnerIdByOpenId(openId));
        }
        visitor.setCommunityId(dto.getCommunityId());
        visitor.setCreateTime(new Date());
        return visitor;
    }

    /**
     * 将实体转化为传输对象
     * @param zyVisitor 实体
     * @return 传输对象
     */
    public VisitorDto transFromVisitor(ZyVisitor zyVisitor){
        if (zyVisitor==null) return null;
        VisitorDto dto = new VisitorDto();
        dto.setVisitorId(zyVisitor.getVisitorId());
        dto.setVisitorDate(zyVisitor.getVisitorDate());
        dto.setVisitorName(zyVisitor.getVisitorName());
        dto.setVisitorPhone(zyVisitor.getVisitorPhoneNumber());
        dto.setCommunityId(zyVisitor.getCommunityId());
        return dto;
    }
}
